
import zipfile
import shutil, os
from pathlib import Path
import datetime
import json
 
def zipDir(dirpath, outFullName, allow=[]):
    """
    压缩指定文件夹
    :param dirpath: 目标文件夹路径
    :param outFullName: 压缩文件保存路径+xxxx.zip
    :return: 无
    """
    zip = zipfile.ZipFile(outFullName, "w", zipfile.ZIP_DEFLATED)
    for path, dirnames, filenames in os.walk(dirpath):
        # 去掉目标跟路径，只对目标文件夹下边的文件及文件夹进行压缩
        fpath = path.replace(dirpath, '')
        for filename in filenames:
            file = os.path.join(path, filename)
            zip.write(os.path.join(path, filename), os.path.join(fpath, filename))
            print(file)
    zip.close()
 

def readJsonFile(path):
    '''
    path: xxx/xx.json
    '''
    # 读取JSON文件
    # with open(path, 'r') as file:
    #     data = json.loads(file)
    #     # 添加一个值
    #     #data['new_key'] = 'new_value'
    #     return data
    f = open(path, 'r', encoding='utf-8')
    if f:
        content = f.read()
        data = json.loads(content)
        f.close()
        return data
def writeJsonFile(path, data):
    # 写入JSON文件
    with open(path, 'w', encoding='utf-8') as file:
        content = json.dumps(data, ensure_ascii=False, indent=4)
        file.write(content)

def createDirs(pathDir):
    #判断文件路径是否存在，如果不存在，则创建，此处是创建多级目录
    if not os.path.isdir(pathDir):
        os.makedirs(pathDir)
def deleteDir(pathDir):
    if os.path.exists(pathDir):
        print(pathDir, '存在删除')
        # 如果要递归删除目录的内容，可使用shutil.rmtree()函数
        shutil.rmtree(pathDir)
    else:
        print(pathDir, ':不存在')

def deleteFile(filePath):
    if os.path.exists(filePath):
        print(filePath, '存在删除')
        # 如果要递归删除目录的内容，可使用shutil.rmtree()函数
        os.remove(filePath)
    else:
        print(filePath, ':不存在')

def fileReName(srcFile, newName):
    os.rename(srcFile, newName)

def copyDir(sourceSrcDir, dstSrcDir):
    #sourceSrcDir = os.getcwd()+os.sep+"src/"
    #dstSrcDir = os.getcwd()+os.sep+"tools/myProj/assets/src/"
    print("\nsrc:", sourceSrcDir, "  \ndst:", dstSrcDir)
    if sourceSrcDir == dstSrcDir:
        #不支持覆盖
        return
    
    if not os.path.exists(sourceSrcDir):
        print(dstSrcDir, '源文件夹不存在，skip')
        return
    if os.path.exists(dstSrcDir):
        print(dstSrcDir, '存在先删除')
        # 如果要递归删除目录的内容，可使用shutil.rmtree()函数
        shutil.rmtree(dstSrcDir)
    else:
        os.makedirs(dstSrcDir)  #创建多级目录
        print(dstSrcDir, '不存在，创建')
        shutil.rmtree(dstSrcDir)
 
    print('拷贝文件夹开始...', sourceSrcDir)
    if os.name == 'nt':  # 判断是否为 Windows 系统
        #避免文件路径过长 导致的错误
        sourceSrcDir = f'\\\\?\\{os.path.abspath(sourceSrcDir)}'
        dstSrcDir = f'\\\\?\\{os.path.abspath(dstSrcDir)}'

    shutil.copytree(sourceSrcDir, dstSrcDir)
    print('拷贝文件夹结束！', dstSrcDir)
    print("")
 
def copyFile(srcFile, dstFile, allowFmt=[]):
    '''
    srcFile, dstFile 绝对路径，
    eg. allowFmt = [".jpg",".bmp"]
    '''
    fileFmt = os.path.splitext(srcFile)[-1]
    for fmt in allowFmt:
        if fileFmt != fmt:
            continue
        if(not os.path.exists(srcFile)):
            print(srcFile, " >>>> not exist")
            break
        else:
            a = 0
        print(srcFile)
        print(dstFile)
        if srcFile == dstFile:
             return True
        res = shutil.copyfile(srcFile, dstFile)
        print(res, ": copy from: ",srcFile)
        return True
    print(fileFmt, "-skip: file format is error",srcFile)
    return False

def recursive_listFiles(path, findSubDir=False):
    '''
    遍历文件夹下所有文件
    '''
    files = os.listdir(path)
    outPathList = []
    outWholePaths = []
    for file in files:
        #file_path = os.path.join(path, file)
        wholePath = os.path.join(path, file)
        
        if os.path.isfile(wholePath):
            outPathList.append(file)
            outWholePaths.append(wholePath)
        elif findSubDir and os.path.isdir(wholePath):
          _path, _wholePath = recursive_listFiles(wholePath,findSubDir)
          outPathList.extend(_path)
          outWholePaths.extend(_wholePath)
    return outPathList, outWholePaths
    

def recursive_listDir(pathDir):
    '''
    遍历文件夹
    '''
    files = os.listdir(pathDir)
    outDirPathList = []
    outDirAllPathList = []
    for file in files:
        #file_path = os.path.join(pathDir, file)
        wholePath = os.path.join(pathDir, file)
        
        if os.path.isfile(wholePath):
            continue
        if os.path.isdir(wholePath):
          outDirPathList.append(file)
          outDirAllPathList.append(wholePath)
    return outDirPathList, outDirAllPathList
    

def filterStr(strInfo, subStr):
    if strInfo.find(subStr) >=0:
        return True
    else:
        return False

def pathExist(path):
    if os.name == 'nt':  # 判断是否是Windows系统
        path = os.fsencode(path)
    return os.path.exists(path)   


if __name__ == "__main__":
    input_path = "./"
    output_path = "./test.zip"
 
    zipDir(input_path, output_path)